/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-08-03
 * Time: 22:03
 */
public class Solution {
    public ListNode middleNode(ListNode head) {
        //使用链表长度的方式
        if (head == null || head.next == null) {
            return head;
        }
        int size = 0;
        ListNode cur = head;
        while (cur != null) {
            size++;
            cur = cur.next;
        }
        //重置cur
        cur = head;
        for (int i = 0; i < size / 2; i++) {
            cur = cur.next;
        }
        return cur;
    }

    public ListNode middleNode1(ListNode head) {
        //处理head是空链表和只有一个元素的情况
        if (head == null || head.next == null) {
            return head;
        }
        //定义快慢指针
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;  //快指针一下走两步
            slow = slow.next;       //慢指针一下走一步
        }
        return slow;
    }
}
